import sqlite3 from "sqlite3";
import { promisify } from "util";

// 数据库文件路径
const DB_PATH = "./db/codebase.db";

// 创建数据库连接池或单例连接
let dbInstance = null;

/**
 * 获取数据库连接实例
 * @returns {Promise<sqlite3.Database>} 数据库连接实例
 */
export async function getDB() {
  if (dbInstance) {
    return dbInstance;
  }

  // 创建新的数据库连接
  const db = new sqlite3.Database(DB_PATH, sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE, (err) => {
    if (err) {
      console.error("Error connecting to database:", err.message);
    } else {
      console.log("Connected to the codebase database.");
    }
  });

  // 将回调风格的方法转换为Promise风格
  db.run = promisify(db.run.bind(db));
  db.all = promisify(db.all.bind(db));
  db.get = promisify(db.get.bind(db));
  db.exec = promisify(db.exec.bind(db));

  dbInstance = db;
  return db;
}